package com.safewind.wx.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.safewind.wx.bean.MessageTemplate;
import com.safewind.wx.bean.TemplateDataItem;
import com.safewind.wx.bean.WebUser;
import com.safewind.wx.constant.WxConstant;
import com.safewind.wx.service.WxService;
import com.safewind.wx.util.DateUtil;
import com.safewind.wx.util.WxSignUtil;
import com.safewind.wx.util.WxUtil;

@Controller
@RequestMapping(value = "/wx")
public class WxController {
    private static final Logger logger = LoggerFactory.getLogger(WxController.class);

    @Resource
    private WxService wxService;

    /**
     * 确认请求来自微信服务器
     */
    @RequestMapping(value = "/connect", method = RequestMethod.GET)
    public void wxsign(@RequestParam(value = "signature", required = false) String signature,

    @RequestParam(value = "timestamp", required = false) String timestamp,

    @RequestParam(value = "nonce", required = false) String nonce,

    @RequestParam(value = "echostr", required = false) String echostr,

    HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (WxSignUtil.checkSignature(signature, timestamp, nonce)) {
            writer.print(echostr);
        } else {
        }
        writer.close();
    }

    /**
     * 处理微信平台发来的消息
     * 
     * @param request
     * @param response
     */
    @RequestMapping(value = "/connect", method = RequestMethod.POST)
    public void handleMessage(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            // 调用核心业务类接收消息、处理消息
            String respMessage = wxService.processRequest(request);
            logger.info("返回给微信平台:{}", respMessage);

            // 响应消息
            PrintWriter out = response.getWriter();
            out.print(respMessage);
            out.close();
        } catch (Exception e) {
            logger.error("处理微信平台消息异常，errorMsg:", e);
        }

    }

    @RequestMapping(value = "/login")
    public ModelAndView login(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("login");
        String openId = null;
        HttpSession session = request.getSession();
        if (session.getAttribute("openId") != null) {
            openId = session.getAttribute("openId").toString();
        } else {
            Object code = request.getParameter("code");
            if (code != null) {
                openId = WxUtil.getWebUser(code.toString()).getOpenid();
            }
        }
        if (openId != null) {
            session.setAttribute("openId", openId);
            String userId = "";// TODO
            if (StringUtils.isNotBlank(userId)) {
                session.setAttribute("userId", userId);
                mav.setViewName("redirect:/wx/case");
            }
        }
        return mav;
    }

    @RequestMapping(value = "/register")
    public ModelAndView register(HttpServletRequest request) throws Exception {
        return new ModelAndView("register");
    }

    @RequestMapping(value = "/logout")
    public void logout(@RequestParam(value = "code", required = false) String code, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        WebUser webUser = WxUtil.getWebUser(code);
        JSONObject res = null;// TODO
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            if ("true".equals(res.getString("result"))) {
                request.getSession().removeAttribute("openId");
                request.getSession().removeAttribute("userId");
                response.getWriter().print("解除绑定成功");
            } else {
                response.getWriter().print(res.getString("message"));
            }
        } catch (IOException e) {
        }
    }

    @RequestMapping(value = "/template")
    public ModelAndView template(@RequestParam(value = "data", required = false) JSONObject data,
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "openId", required = false) String openId) throws Exception {
        WebUser webUser = WxUtil.getWebUser(code);
        openId = webUser.getOpenid();

        MessageTemplate mt;
        String color = "#feb91a";
        Map<String, TemplateDataItem> map = new HashMap<String, TemplateDataItem>();
        TemplateDataItem tdi = new TemplateDataItem("您有一条待办任务要处理", color);
        map.put("first", tdi);
        tdi = new TemplateDataItem("这里是待办内容", color);
        map.put("keyword1", tdi);
        tdi = new TemplateDataItem(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"), color);
        map.put("keyword2", tdi);
        tdi = new TemplateDataItem("北京天安门", color);
        map.put("keyword3", tdi);
        tdi = new TemplateDataItem("ok", color);
        map.put("remark", tdi);

        mt = new MessageTemplate();
        mt.setTouser(openId);
        mt.setTemplate_id(WxConstant.TEMPLATE_ID);
        mt.setUrl("");
        mt.setData(map);
        WxUtil.SendTemplateMessage(mt);
        ModelAndView mav = new ModelAndView();
        mav.setViewName("main");
        mav.addObject("openId", webUser.getOpenid());
        return mav;
    }


    @RequestMapping(value = "/getJsApi")
    @ResponseBody
    public Object getJsApi(HttpServletRequest request) {
        String url = request.getParameter("url");
        return WxUtil.makeWXTicket(url);
    }

}
